<template>
  <div class="param-desc">
    <h3>{{ title }}</h3>
    <div ref="hide" class="desc-hide"><slot></slot></div>
    <div ref="table"></div>
  </div>
</template>

<script>
export default {
  alias: 'ParamDesc',
  name: "ParamDesc",
  props: {
    title: {
      type: String,
      default: "",
    },
  },
  mounted() {
    this.renderTable();
  },
  methods: {
    renderTable() {
      function handlerEmptyStr(str) {
        return str.trim() === '' ? '—' : str.trim();
      }
      const table = this.$refs.table;
      const hide = this.$refs.hide;
      const str = hide.innerText;
      const rows = this.getRows(str);
      const column_flex = [];
      const column_align = [];
      for (const row of rows) {
        const rowEl = document.createElement('div');
        rowEl.classList.add('desc-row');
        rowEl.classList.add(row.isTitle ? 'desc-color-title' : 'desc-color-normal');
        for (let i = 0; i < row.values.length; i++) {
          const value = row.values[i];
          const valueEl = document.createElement('div');
          valueEl.classList.add('desc-row-item');
          if (!column_flex[i]) column_flex[i] = 1;
          if (!column_align[i]) column_align[i] = 'left';
          if (typeof value === 'string') {
            valueEl.innerHTML = handlerEmptyStr(value);
          } else if (typeof value === 'object') {
            valueEl.innerHTML = handlerEmptyStr(value.text);
            if (row.isTitle && column_flex[i] === 1) {
              column_flex[i] = value.flex || 1;
            }
            if (row.isTitle && column_align[i] === 'left') {
              column_align[i] = value.align || 'left';
            }
          }
          valueEl.style.flex = column_flex[i] || 1;
          valueEl.style.justifyContent = column_align[i] === 'center' ? 'center' : (column_align[i] === 'right' ? 'flex-end' : 'flex-start');
          rowEl.appendChild(valueEl);
        }
        table.appendChild(rowEl);
      }
    },
    getRows(str) {
      const rows = [];
      let count = 0;
      let s = '';
      for (const c of str) {
        s += c;
        if (c === '{') count++;
        else if (c === '}') {
          count--;
          if (count === 0) {
            rows.push(JSON.parse(s));
            s = '';
          }
        }
      }
      return rows;
    }
  },
};
</script>

<style lang="scss">
.param-desc {
  margin-top: 50px;
}
.desc-hide {
  opacity: 0;
  height: 0;
}
.desc-row {
  display: flex;
  border-bottom: 1px solid #ccc;
  .desc-row-item {
    flex: 1;
    padding: 10px 5px;
    display: flex;
    align-items: center;
    word-break: break-all;
  }
}
.desc-color-normal {
  color: #606266;
}
.desc-color-title {
  color: #909399;
}
</style>